package linces

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
)

// 解密
func decrypt(ciphertext string, key []byte) (string, error) {
	ciphertextBytes, _ := base64.StdEncoding.DecodeString(ciphertext)
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	if len(ciphertextBytes) < aes.BlockSize {
		return "", fmt.Errorf("ciphertext too short")
	}
	iv := ciphertextBytes[:aes.BlockSize]
	ciphertextBytes = ciphertextBytes[aes.BlockSize:]
	// 使用 CBC 模式进行解密
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(ciphertextBytes, ciphertextBytes)
	// 去掉填充
	plaintext, err := unpad(ciphertextBytes)
	if err != nil {
		return "", err
	}
	return string(plaintext), nil
}

func GetDecryCode(authCode string, AesKey []byte) string {
	// 解析授权码（解密）
	decryptedCode, err := decrypt(authCode, AesKey)
	if err != nil {
		fmt.Println("Error decrypting:", err)
		return ""
	}
	return decryptedCode
}
